<template>
    <div class="order-refund-apply-list">
        <van-nav-bar title="申请退款" :border="false" fixed placeholder/>
        <van-form @submit="handleApplyRefund">
            <white-space/>
            <van-field name="kind" :value="kindLabel" label="退款方式"
                       input-align="right" readonly/>
            <white-space/>
            <order-refund-apply-list-item v-for="(item, index) in items" :key="item.id" :index="index" :item="item"
                                          :name="item.name" :image-url="item.imageUrl"
                                          :quantity="item.quantity"
                                          :refunding-amount="item.refundingAmount"
                                          :refunded-amount="item.refundedAmount"
                                          :total-amount="item.totalAmount"/>
            <van-cell title="退款总金额" :value="'¥ ' + totalRefundingAmount" value-class="order-refund-total-refunding-amount"/>
            <white-space/>
            <div style="margin: 16px;">
                <van-button round block type="danger" native-type="submit" :loading="applying">提交申请</van-button>
            </div>
            <white-space/>
        </van-form>
    </div>
</template>

<script>
  import BigDecimal from "decimal.js"
  import * as _ from "lodash"
  import { message, order as Order } from "@mall/api-services"
  import WhiteSpace from "@/components/WhiteSpace"
  import { Button, Cell, CellGroup, Field, Form, NavBar, Toast } from "vant"
  import OrderRefundApplyListItem from "@/views/order/OrderRefundApplyListItem"

  const { OrderRefundKind } = Order
  export default {
    name: "OrderRefundApplyList",
    components: {
      OrderRefundApplyListItem,
      WhiteSpace,
      [Button.name]: Button,
      [Cell.name]: Cell,
      [CellGroup.name]: CellGroup,
      [NavBar.name]: NavBar,
      [Field.name]: Field,
      [Form.name]: Form,
    },
    props: {
      orderId: String,
      itemIds: Array,
      kind: String,
    },
    watch: {
      "$route": "refreshOrder",
      order(order) {
        const { itemIds } = this
        this.items = _.chain(order.items)
          .filter(item => _.includes(itemIds, item.id))
          .map(item => ({
            itemId: item.id,
            name: item.name,
            imageUrl: item.imageUrl,
            quantity: item.quantity,
            refundingAmount: item.refundingAmount,
            refundedAmount: item.refundedAmount,
            totalAmount: item.totalAmount,
            amount: BigDecimal.sub(item.totalAmount, BigDecimal.add(item.refundedAmount, item.refundingAmount)).toNumber(),
          }))
          .value()
      },
    },
    created() {
      this.refreshOrder()
    },
    computed: {
      kindLabel() {
        const { kind } = this
        if (kind === OrderRefundKind.OnlyRefund) {
          return "仅退款"
        } else if (kind === OrderRefundKind.ReturnRefund) {
          return "退货退款"
        }
        return "未知"
      },
      totalRefundingAmount() {
        return _.chain(this.items)
          .map(item => _.isEmpty(item.amount) ? 0 : item.amount)
          .reduce((sum, n) => BigDecimal.add(sum, n).toNumber(), 0)
          .value()
      },
    },
    data() {
      return {
        order: new Order.Order(),
        refund: new Order.OrderRefund(),
        items: [],
        applying: false,
      }
    },
    methods: {
      refreshOrder() {
        if (this.showKind) {
          return
        }
        Toast.loading()
        Order.OrderServiceV1
          .getOrder(this.orderId)
          .then(order => this.order = order)
          .catch(({ response }) => Toast(message.getResponseMessage(response)))
          .finally(() => Toast.clear())
      },
      handleApplyRefund() {
        const { orderId } = this
        const refund = _.assign(new Order.OrderRefund(), {
          kind: this.kind,
          items: _.map(this.items, item => _.assign(new Order.OrderRefundItem(), {
            itemId: item.itemId,
            itemStatus: item.itemStatus,
            name: item.name,
            amount: item.amount,
            imageUrl: item.imageUrl,
            notes: item.notes,
          })),
        })

        this.applying = true
        Order.OrderServiceV1.applyOrderRefund(orderId, refund)
          .then(() => new Promise(resolve => {
            Toast.success({
              message: "申请成功",
              duration: 2000,
              onClose: resolve,
            })
          }))
          .then(() => this.$router.go(-3))
          .catch(({ response }) => Toast(message.getResponseMessage(response)))
          .finally(() => this.applying = false)
      },
    },
  }
</script>

<style lang="scss" scoped>
    @import "../../styles/variables";

    .order-refund-apply-list {
        .order-refund-total-refunding-amount {
            color: $orange-dark;
        }
    }
</style>
